import { chalkERROR, chalkSUCCESS } from "@/utils/chalkTip";
import { logger } from "@/utils/logger";
import mysql2 from "mysql2";

const mysqlInfo = {
    host: "localhost",
    port: 3306,
    database: "db_warehouse",
    user: "root",
    password: "123456"
};

// 1. 创建连接池
const connectionPool = mysql2.createPool(mysqlInfo);

// 2.获取连接是否成功
connectionPool.getConnection((err, connection) => {
    // 1.判断是否有错误信息
    if (err) {
        logger.debug(chalkERROR("获取数据库连接失败~"), err.message);
        return;
    }

    // 2.获取connection, 尝试和数据库建立一下连接
    connection.connect(err => {
        if (err) {
            logger.debug(chalkERROR("和数据库交互失败~"), err);
        } else {
            logger.debug(chalkSUCCESS("数据库连接成功, 可以操作数据库!"));
        }
    });
});

// 3.获取连接池中连接对象(promise)
const connection = connectionPool.promise();

export default connection;
